<template>
  <!---搜索表单-->
    <div class="search-div">
        <el-form label-width="80px" size="small">
            <el-row :gutter="24">
                <el-col :span="6">
                    <el-form-item label="教学班名称">
                        <el-input v-model="queryDto.name" placeholder="请输入课程名称"/>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="课程名称">
                        <el-select v-model="queryDto.courseId" style="width: 100%" filterable placeholder="请选择课程">
                            <el-option v-for="item in courseList" :key="item.id" :value="item.id"
                                       :label="item.name"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="代课教师">
                        <el-select v-model="queryDto.teacherId" style="width: 100%" filterable placeholder="请选择教师">
                            <el-option v-for="item in teacherList" :key="item.id" :value="item.id"
                                       :label="item.name"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="学年">
                        <el-select v-model="queryDto.academicYear" style="width: 100%" placeholder="请选择学年">
                            <el-option v-for="(label,value) in yearOptions" :key="label" :value="value" :label="label"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="学期">
                        <el-select v-model="queryDto.semester" style="width: 100%" placeholder="请选择学期">
                            <el-option v-for="(label,value) in semesterOptions" :key="label" :value="value"
                                       :label="label"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col>
                    <el-button type="primary" size="small" @click="searchTeachingClass"> 搜索</el-button>
                    <el-button size="small" @click="resetData">重置</el-button>
                </el-col>
            </el-row>
        </el-form>
    </div>

  <!--添加按钮-->
    <div class="tools-div">
        <el-button type="success" size="small" @click="addShow">添 加</el-button>
    </div>
    <el-dialog v-model="dialogVisible" title="添加或修改" width="30%" @close="handleDialogClose">
        <el-form label-width="100px" :model="teachingClass" ref="teachingClassForm" :rules="rules">
            <el-form-item label="教学课程" prop="courseId">
                <el-select v-model="teachingClass.courseId" @change="getTeacherByCourseId"
                           placeholder="请选择或输入课程名称" filterable>
                    <el-option v-for="item in courseOptions" :key="item.id" :value="item.id"
                               :label="item.name"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="教学班名称" prop="name">
                <el-input v-model="teachingClass.name" placeholder="请输入教学班名称"/>
            </el-form-item>
            <el-form-item label="代课教师" prop="teacherId">
                <el-select v-model="teachingClass.teacherId" placeholder="请先选择课程">
                    <el-option v-for="item in teacherOptions" :key="item.id" :value="item.id"
                               :label="item.name"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="最大人数" prop="maxCount">
                <el-input-number v-model="teachingClass.maxCount" min="0"/>
            </el-form-item>
            <el-form-item label="学年" prop="academicYear">
                <el-select v-model="teachingClass.academicYear" placeholder="请选择或输入课程名称">
                    <el-option v-for="(label,value) in yearOptions" :key="label" :value="value" :label="label"/>
                </el-select>
            </el-form-item>
            <el-form-item label="学期" prop="semester">
                <el-select v-model="teachingClass.semester" placeholder="请选择或输入课程名称">
                    <el-option v-for="(label,value) in semesterOptions" :key="label" :value="value" :label="label"/>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submit">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <el-dialog title="关联行政班级" v-model="dialogVisibleStudent" draggable width="30%"
               @close="handleDialogCloseStudent">
        <el-form :model="form" label-width="100px">
            <el-form-item label="教学班名称">
                <el-input v-model="form.className" disabled/>
            </el-form-item>
            <el-form-item label="班级">
                <el-select v-model="form.classId" placeholder="请选择班级" filterable>
                    <el-option v-for="classItem in classOptions"
                               :key="classItem.id" :value="classItem.id"
                               :label="classItem.name"/>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm">提交</el-button>
                <el-button @click="dialogVisibleStudent = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

  <!---数据表格-->
    <el-table :data="list" style="width: 100%" border>
        <el-table-column type="index" label="序号" width="60px" align="center"/>
        <el-table-column prop="name" label="教学班名称" min-width="200px"/>
        <el-table-column prop="courseName" label="教学课程" min-width="180px"/>
        <el-table-column prop="teacherName" label="教学老师" min-width="100px"/>
        <el-table-column prop="academicYear" label="学年" #default="scope" min-width="110px">
            {{ yearOptions[scope.row.academicYear] }}
        </el-table-column>
        <el-table-column prop="semester" label="学期" #default="scope" min-width="100px">
            <el-tag v-if="scope.row.semester" :type="scope.row.semester == 1?'danger':'success'">{{
                semesterOptions[scope.row.semester]
                }}
            </el-tag>
        </el-table-column>
        <el-table-column prop="classesName" label="行政班" min-width="180px"/>
        <el-table-column prop="maxCount" label="最大人数" width="130px"/>
        <el-table-column prop="studentNum" label="已选人数" width="100px"/>
        <el-table-column prop="createTime" label="创建时间" width="160px" align="center"/>
        <el-table-column prop="updateTime" label="更新时间" width="160px" align="center"/>
        <el-table-column label="操作" align="center" #default="scope" width="240px" fixed="right">
            <el-button type="warning" size="small" @click="addStudent(scope.row)">设置行政班级</el-button>
            <el-button type="primary" size="small" @click="editTeachingClass(scope.row)">修改</el-button>
            <el-button type="danger" size="small" @click="deleteById(scope.row)">删除</el-button>
        </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="pageParams.page" v-model:page-size="pageParams.limit"
                   :page-sizes="[5, 10, 20, 50, 100]" @size-change="fetchData" @current-change="fetchData"
                   layout="total, sizes, prev, pager, next" :total="total"/>
</template>

<!-- script部分修改内容 -->
<script setup>
import {onMounted, reactive, ref} from 'vue'
import {FindAllCourse} from "@/api/course";
import {ElMessage, ElMessageBox} from "element-plus";
import {
    DeleteTeachingClassById,
    FindAllClassByTeachingClass,
    GetTeachingClassByPage,
    SaveStudentToTeachingClassByClassesId,
    SaveTeachingClass,
    UpdateTeachingClass
} from "@/api/teachingClass";
import {FindAllTeacher, FindTeacherByCourseId} from "@/api/teacher";

const courseList = ref([])
const teacherList = ref([])
const dialogVisible = ref(false)
const dialogVisibleStudent = ref(false)
const classOptions = ref([])
const form = reactive({
    teachingClassId: '',
    className: '',
    classId: ''
})
const courseOptions = ref([])
const teacherOptions = ref([])
const yearOptions = {
    2024: "2024-2025",
    2023: "2023-2024",
    2022: "2022-2023",
    2021: "2021-2022",
    2020: "2020-2021",
    2019: "2019-2020"
};

const semesterOptions = {
    1: "秋季学期",
    2: "春季学期"
};
//添加教学班
const addStudent = async (row) => {
    form.teachingClassId = row.id
    form.className = row.name
    form.classId = row.classesId
    dialogVisibleStudent.value = true
    const {data} = await FindAllClassByTeachingClass(row.courseId, row.academicYear, row.semester);
    classOptions.value = data
}
//
const submitForm = async () => {
    const {code} = await SaveStudentToTeachingClassByClassesId(form.teachingClassId, form.classId)
    if (code === 200) {
        ElMessage.success("添加成功")
        dialogVisibleStudent.value = false
        await fetchData()
    } else ElMessage.error("添加失败,请检查该班级数据")
}
const handleDialogCloseStudent = () => {
    form.className = ''
    form.classId = ''
}

const defaultParams = {
    id: '',
    name: '',
    courseId: '',
    teacherId: '',
    courseName: '',
    teacherName: '',
    maxCount: '',
    academicYear: '',
    semester: '',
}
const teachingClass = ref(defaultParams)
const teachingClassForm = ref('teachingClassForm')
// 添加修改
const submit = async () => {
    teachingClassForm.value.validate(async (valid) => {
        if (valid) {
            if (teachingClass.value.id) {
                const {code} = await UpdateTeachingClass(teachingClass.value)
                if (code === 200) {
                    ElMessage.success("修改成功")
                } else ElMessage.error("修改失败,请检查表单数据")
            } else {
                const {code} = await SaveTeachingClass(teachingClass.value)
                if (code === 200) {
                    ElMessage.success("添加成功")
                } else ElMessage.error("添加失败,请检查表单数据")
            }
            await fetchData()
            dialogVisible.value = false
            teachingClassForm.value.resetFields()
        } else {
            ElMessage.error("表单数据校验失败")
        }
    });

}
const handleDialogClose = () => {
    dialogVisible.value = false
    teacherOptions.value = []
    teachingClassForm.value.resetFields()
    teachingClass.value = {...defaultParams}
}

// 分页条总记录数
let total = ref(0)
// 定义表格数据模型
let list = ref([])
//分页数据
const pageParamsForm = {
    page: 1, // 页码
    limit: 10, // 每页记录数
}
const pageParams = ref(pageParamsForm) // 将pageParamsForm包装成支持响应式的对象

// 页面加载完毕以后请求后端接口获取数据
onMounted(async () => {
    await fetchCourseOptions()
    await fetchData()
    await getTeacherList()
    await getCourseList()
})
const getCourseList = async () => {
    const {data} = await FindAllCourse();
    courseList.value = data
}
const getTeacherList = async () => {
    const {data} = await FindAllTeacher()
    teacherList.value = data
}
const getTeacherByCourseId = async () => {
    const {data} = await FindTeacherByCourseId(teachingClass.value.courseId)
    teacherOptions.value = data
}
const fetchCourseOptions = async () => {
    const {data} = await FindAllCourse();
    courseOptions.value = data
}

const queryDto = ref({
    name: '',
    courseId: '',
    teacherId: '',
    academicYear: '',
    semester: ''
})
// 搜索按钮点击事件处理函数
const searchTeachingClass = () => {
    fetchData()
}
const addShow = () => {
    teachingClass.value = {...defaultParams}
    dialogVisible.value = true
}
// 重置按钮点击事件处理函数
const resetData = () => {
    queryDto.value = {}
    fetchData()
}
const editTeachingClass = async row => {
    const {data} = await FindTeacherByCourseId(row.courseId)
    teacherOptions.value = data
    teachingClass.value = row
    // 修改按钮点击事件处理函数
    dialogVisible.value = true
}
const deleteById = (row) => {
    ElMessageBox.confirm("此操作将永久删除该记录, 是否继续?", "Warning", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        const {code} = await DeleteTeachingClassById(row.id)
        if (code === 200) {
            ElMessage.success('删除成功')
            pageParams.value.page = 1
            await fetchData()
        }
    })
}

// 远程调用后端分页查询接口
const fetchData = async () => {
    const {data} = await GetTeachingClassByPage(
        pageParams.value.page,
        pageParams.value.limit,
        queryDto.value
    )
    list.value = data.list
    total.value = data.total
}
const rules = reactive({
    name: [{required: true, message: '请输入课程名称', trigger: 'blur'}],
    courseId: [{required: true, message: '请选择课程', trigger: 'charge'}],
    teacherId: [{required: true, message: '请选择老师', trigger: 'charge'}],
    maxCount: [{required: true, message: '请输入最大人数', trigger: 'blur'}],
    academicYear: [{required: true, message: '请选择学年', trigger: 'charge'}],
    semester: [{required: true, message: '请选择学期', trigger: 'charge'}]
})
</script>

<style scoped>
.search-div {
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 3px;
    background-color: #fff;
}

.tools-div {
    margin: 10px 0;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 3px;
    background-color: #fff;
}
</style>
